package serial;

import java.util.ArrayList;

public class EchoCounter implements SerialReaderListener {
	private int numEchoesReceived, numEchoesExpected;
	private boolean awaitingEchoes;
	private ArrayList<AllEchoesReceivedListener> listeners;
	
	public EchoCounter() {
		reset();
		listeners = new ArrayList<AllEchoesReceivedListener>();
	}
	
	private void reset() {
		numEchoesExpected = numEchoesReceived = 0;
		awaitingEchoes = false;
	}
	
	public void addAllEchoesReceivedListener(AllEchoesReceivedListener aerl) {
		if (aerl == null) {
			System.out.println("What???");
			throw new IllegalArgumentException("Null listener?");
		}
		listeners.add(aerl);
	}
	
	public void msgSent(String msg) {
		int lines = 0;
    	for (int i = 0; i < msg.length(); ++i) {
    		if (msg.codePointAt(i) == '\n') {
    			++lines;
    		}
    	}
    	if (lines > 0) {
    		numEchoesExpected += lines;
    		awaitingEchoes = true;
    	}
	}
	
	public void stringReceived(String input) {
		for (int i = 0; i < input.length(); ++i) {
			if (input.charAt(i) == '\n') {
				numEchoesReceived++;
			}
		}
		
		if (allEchoesReceived() && awaitingEchoes) {
			awaitingEchoes = false;
			for (AllEchoesReceivedListener listener: listeners) {
				listener.allEchoesReceived();
			}
			//System.out.println("echoes: " + numEchoesReceived + "(" + numEchoesExpected + ") input:\"" + input + "\"");
		}
	}

	public void unplugged() {
		reset();
	}
	
	public boolean allEchoesReceived() {
		return numEchoesExpected <= numEchoesReceived;
	}

	public void halted() {
		reset();
	}
}
